package io.flutter.plugins

import android.app.Activity
import android.util.Log
import androidx.annotation.NonNull
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding


/** BasePlugin */
class BasePlugin : FlutterPlugin, HostMessageApi, ActivityAware {

    companion object {
        private var flutterMessageApi: FlutterMessageApi? = null
        fun getFlutterMessageApi(): FlutterMessageApi? {
            return flutterMessageApi
        }
    }

    private var activity: Activity? = null
    private var tag = "BasePlugin"
    override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
        Log.e(tag, "onAttachedToEngine-start")
        HostMessageApi.setUp(flutterPluginBinding.binaryMessenger, this)
        flutterMessageApi = FlutterMessageApi(flutterPluginBinding.binaryMessenger)
        Log.e(tag, "onAttachedToEngine-end")
    }

    override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
        HostMessageApi.setUp(binding.binaryMessenger, null)
    }

    override fun flutter2Native(message: String, type: Long): String {
        print("flutter2Native=message=start=>$message=type=$type")
        return "flutter2Native=message=$message=type=$type"
    }

    override fun flutter2NativeAsync(
        message: String,
        type: Long,
        callback: (Result<String>) -> Unit
    ) {
        print("flutter2NativeAsync=message=$message=type=$type")
        callback(Result.success("flutter2NativeAsync=message=$message=type=$type"))
        if (type == 1L) {
            closeCurrentActivity()
        }
    }

    private fun closeCurrentActivity() {
        activity?.finish()
    }

    override fun onAttachedToActivity(binding: ActivityPluginBinding) {
        this.activity = binding.activity
    }

    override fun onDetachedFromActivityForConfigChanges() {

    }

    override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {

    }

    override fun onDetachedFromActivity() {
        this.activity = null
    }
}